<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>incremental md5</title>
		<style>
			body{text-align:center;font:13px Tahoma}
			form{margin:9vh auto}
			pre{background:#ffd;border:1px solid orange;padding:1em;margin:0 auto;display:none;text-align:left;line-height:1.25}
		</style>
	</head>
	<body>
		<h1>incremental md5 demo</h1>
		<h3>with <a target="_blank" href="//github.com/satazor/SparkMD5">GitHub SparkMD5</a> &nbsp;&nbsp;&nbsp;<a target="_blank" href="spark-md5.min.js">download spark-md5.min.js</a></h3>
		<form method="POST" enctype="multipart/form-data" onsubmit="return false;" ><input id=file type=file placeholder="select a file" /></form>
		<pre id=log></pre>
		<script src="spark-md5.min.js"></script>
		<script>
			var log=document.getElementById("log");
			document.getElementById("file").addEventListener("change", function() {
				var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
					file = this.files[0],
					chunkSize = 2097152, // read in chunks of 2MB
					chunks = Math.ceil(file.size / chunkSize),
					currentChunk = 0,
					spark = new SparkMD5.ArrayBuffer(),
					frOnload = function(e){
						log.innerHTML+="\nread chunk number "+parseInt(currentChunk+1)+" of "+chunks;
						spark.append(e.target.result); // append array buffer
						currentChunk++;
						if (currentChunk < chunks)
							loadNext();
						else
						   log.innerHTML+="\nfinished loading :)\n\ncomputed hash:\n"+spark.end()+"\n\nyou can select another file now!\n";
					},
					frOnerror = function () {
						log.innerHTML+="\noops, something went wrong.";
					};
				function loadNext() {
					var fileReader = new FileReader();
					fileReader.onload = frOnload;
					fileReader.onerror = frOnerror;
					var start = currentChunk * chunkSize,
						end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
					fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
				};
				log.style.display="inline-block";
				log.innerHTML="file name: "+file.name+" ("+file.size.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ',')+" bytes)\n";
				loadNext();
			});
		</script>
	</body>
</html>